package org.jeecg.demo.wx.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.demo.wx.common.WXLoginUser;
import org.jeecg.demo.wx.constant.CacheConstant;
import org.jeecg.demo.wx.request.WXLoginRequest;
import org.jeecg.demo.wx.response.WXLoginResponse;
import org.jeecg.demo.wx.service.WXLoginService;
import org.jeecg.demo.wx.util.WXApiUtil;
import org.jeecg.demo.wx.util.WXJWTUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 功能描述
 * 小程序登录实现类
 *
 * @author: zgq
 * @date: 2024年01月29日 13:07
 */
@Service
public class WXLoginServiceImpl implements WXLoginService {

    @Autowired
    private WXApiUtil wxApiUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;


    @Override
    public Result<JSONObject> login(WXLoginRequest request) {
        Result<JSONObject> result = new Result<>();
        JSONObject jsonObject = new JSONObject();
        String code = request.getCode();
        WXLoginResponse wxLoginResponse = wxApiUtil.login(code);
        String openid = wxLoginResponse.getOpenid();
        if (queryUserNotExist(openid)) {
            saveNewUser(openid);
        }
        String session_key = wxLoginResponse.getSession_key();
        String jwt = WXJWTUtil.sign(openid, session_key);
        WXLoginUser wxLoginUser = WXLoginUser.builder().sessionKey(session_key).build();
        redisUtil.set(CacheConstant.WX_USER_LOGIN_KEY + openid, wxLoginUser, WXJWTUtil.EXPIRE_TIME);
        jsonObject.put("token", jwt);
        result.setResult(jsonObject);
        return result;
    }

    private void saveNewUser(String openid) {
        SysUser newSysUser = new SysUser();
        newSysUser.setUsername(openid);
        sysUserService.save(newSysUser);
    }

    private boolean queryUserNotExist(String openid) {
        SysUser sysUser = sysUserService.lambdaQuery().eq(SysUser::getUsername, openid).one();
        return sysUser == null;
    }
}
